package cn.wang.gageway.filter;

import cn.wang.auth.utils.JwtUtils;
import cn.wang.common.utils.CookieUtils;
import cn.wang.gageway.config.AllowPathConfig;
import cn.wang.gageway.config.LyAuthProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private LyAuthProperties authProperties;
    @Autowired
    private AllowPathConfig allowPathConfig;


    @Override
    public String filterType() {
        return "pre"; // 在转发之前进行拦截
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        // 配置白名单
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 如果放行一些不需要登录的请求
        List<String> allowPaths = allowPathConfig.getAllowPaths();
        String path = request.getRequestURL().toString();// 获取请求的全路径
        for (String allowPath : allowPaths) {
            if (path.contains(allowPath)){
                return false;
            }
        }
        return true;    // true执行run方法, false不执行
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 校验是否登录, 登录了放行, 没有拦截
        String token = CookieUtils.getCookieValue(request, authProperties.getTokenName());
        try {
            JwtUtils.getInfoFromToken(token, authProperties.getPublicKey());
        } catch (Exception e) {
            ctx.setSendZuulResponse(false);// 不转发
            ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value()); // 响应状态码401
            e.printStackTrace();
        }
        return null;
    }
}
